package com.example;

import com.example.auth.AuthHandler;
import com.example.auth.JwtProvider;
import com.example.db.DatabaseConfig;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Promise;
import io.vertx.ext.jdbc.JDBCClient;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.handler.BodyHandler;
import io.vertx.ext.web.handler.JWTAuthHandler;

public class MainVerticle extends AbstractVerticle {
    @Override
    public void start(Promise<Void> startPromise) {
        JDBCClient db = DatabaseConfig.createClient(vertx);
        JwtProvider jwtProvider = new JwtProvider(vertx);
        AuthHandler authHandler = new AuthHandler(db, jwtProvider);

        Router router = Router.router(vertx);
        router.route().handler(BodyHandler.create());

        router.post("/api/register").handler(authHandler::register);
        router.post("/api/login").handler(authHandler::login);

        router.get("/api/hello").handler(JWTAuthHandler.create(jwtProvider.getProvider()))
              .handler(ctx -> ctx.response().end("Hello, authenticated user!"));

        vertx.createHttpServer().requestHandler(router).listen(8888, http -> {
            if (http.succeeded()) {
                startPromise.complete();
                System.out.println("Server started at http://localhost:8888");
            } else {
                startPromise.fail(http.cause());
            }
        });
    }
}